<template>
  <el-dialog :visible.sync="openSelectRule" width="1200px" append-to-body :before-close="handleClose">
    <div class="app-container">
      <el-row :gutter="10" class="mb8">
        <el-col :span="5">
          <el-button type="primary" plain size="medium" @click="addBox">添加</el-button>
        </el-col>
      </el-row>
      <div class="box" v-for="(box, boxIndex) in boxes" :key="boxIndex">
          <el-form ref="detailForm" :model="detailForm[boxIndex]">
            <el-card>
              <div style="line-height: 50px; height: 50px; display: flex; font-size: 16px">
                <label>条件名称：</label>{{box.conditionName}}
              </div>
              <div style="display: flex; align-items: center;">
                <h3>如果</h3>
                <el-button type="primary" plain icon="el-icon-plus"  style="margin-left: 10px; float: left;" @click="addRule(boxIndex, box.ruleId, box.formId)" />
                <el-button type="danger" plain icon="el-icon-delete"  style="margin-left: 10px; float: left;" @click="deleteBox(boxIndex, box.ruleId)" />
              </div>
              <div>
                <ul class="rule-main" v-for="(rule, ruleIndex) in box.rules" :key="ruleIndex" style="display: flex; width: 100%">
                  <li class="connector-model">
                    <el-form-item>
                      <el-select v-model="rule.columnCondition" placeholder="请选择" style="width: 100%" :required="true">
                        <el-option v-for="item in connectorOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </li>
                  <li class="select-model">
                    <el-form-item>
                      <el-select v-model="rule.fieldName" placeholder="请选择或输入" style="width: 100%" :required="true" :clearable="true" :allow-create="true" :filterable = "true" :multiple-limit="1">
                        <el-option v-for="item in fieldNameOption" :key="item.fieldName" :label="item.fieldCaption" :value="item.fieldName" :type="item.fieldType"></el-option>
                      </el-select>
                    </el-form-item>
                  </li>
                  <li class="fuhao-model">
                    <el-select v-model="rule.condition" placeholder="请选择" style="width: 100%" :required="true">
                      <el-option v-for="item in fuhaoOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                  </li>
                  <li class="type-model">
                    <el-form-item>
                      <el-select v-model="rule.isStatic" placeholder="请选择" style="width: 100%" :required="true">
                        <el-option v-for="item in typeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
                      </el-select>
                    </el-form-item>
                  </li>
                  <li class="input-mpdel">
                    <div v-if="rule.isStatic === '1'">
                      <el-input v-model="rule.staticValue" placeholder="请输入" style="width: 100%" :required="rule.isStatic === '1'"></el-input>
                    </div>
                    <div v-else>
                      <el-select v-model="rule.dynamicValue" placeholder="请选择" style="width: 100%" :required="rule.isStatic === '0'">
                        <el-option v-for="dict in dict.type.FORM_RULE_DYNAMIC_VALUE" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                      </el-select>
                    </div>
                  </li>
                  <li>
                    <el-button type="danger" plain icon="el-icon-delete"  style="margin-left: 10px;" @click="deleteRule(boxIndex, ruleIndex, rule)" />
                  </li>
                </ul>
              </div>
              <div>
                <h3>那么</h3>
                <h3 style="margin-left: 5%">分单</h3>
              </div>
            </el-card>
          </el-form>
        </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button type="info" @click="handleClose">取消</el-button>
      <el-button type="primary" @click="addChildRule">确定</el-button>
    </div>

    <el-dialog title="新增规则" :visible.sync="ruleOpen" width="30%" style="margin-top:8%;" append-to-body>
      <el-form ref="ruleForm" :model="ruleForm" :rules="ruleRules" label-width="100px">
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.conditionName" placeholder="请输入名称" maxlength="30" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addParentRule">确 定</el-button>
        <el-button @click="ruleOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
import {
  addRULE,
  addRule,
  addRuleBatch,
  childList,
  delChildRule,
  delParentRule,
  delRULE,
  getRULE,
  listNoPage,
  listRULE,
  ruleList,
  updateRULE
} from "@/api/archive/RULE";

export default {
  archive_Dicts: ['FORM_RULE_DYNAMIC_VALUE','FORM_RULE_CONDITION_TEXT','FORM_RULE_CONDITION_NUMBER','FORM_RULE_CONDITION_DATE'],
  props:{
    openSelectRule:{
      type:Boolean,
      default:false,
    },
  },
  name: "RULE",
  data() {
    return {
      // 表单id
      formId: "",
      // 存储分单大盒子的数组
      boxes: [],
      // 动态盒子分单规则
      dropdowns: [],
      // 连接符下拉框
      connectorOption: [
        {value: "and", label: "和"},
        {value: "or", label: "或"},
      ],
      // 表头参数下拉框
      fieldNameOption: [],
      // 判断符号下拉框
      fuhaoOption: [],
      // 类型下拉框
      typeOption: [
        {value: "1", label: "静态"},
        {value: "0", label: "动态"},
      ],
      // 规则表单
      detailForm: {},
      // 规则名称弹框
      ruleOpen: false,
      // 规则名称表单
      ruleForm: {
        conditionName: undefined
      },
      // 规则表单校验
      ruleRules: {
        conditionName: [
          { required: true, message: "规则不能为空", trigger: "blur" }
        ]
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 分单规则表格数据
      RULEList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ruleId: null,
        formId: null,
        fieldName: null,
        condition: null,
        fieldType: null,
        isStatic: null,
        dynamicValue: null,
        staticValue: null,
        conditionName: null,
        groupId: null,
        type:null,
        columnCondition:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  watch:{
    'boxes': {
      handler: function(newBoxes) {
        // 监听boxes的变化，更新rule.fuhao的选项列表
        for (let i = 0; i < newBoxes.length; i++) {
          const box = newBoxes[i];
          for (let j = 0; j < box.rules.length; j++) {
            const rule = box.rules[j];
            const selectedfieldName = this.fieldNameOption.find(option => option.fieldName === rule.fieldName);
            if(selectedfieldName != undefined) {
              // console.log(selectedfieldName.fieldType,selectedfieldName)
              this.getFuhaoOptions(selectedfieldName.fieldType);
            } else {
              this.getFuhaoOptions()
            }
          }
        }
      },
      deep: true
    }
  },
  created() {
    // this.getList();
  },
  methods: {
    init(detailId) {
      this.formId = detailId
      this.getParent();
      this.form = {
        detailId: detailId
      }
      listNoPage(this.form).then(response => {
        this.fieldNameOption = response.map((item) => {
          return {
            fieldCaption: item.fieldCaption,
            fieldName: item.columnName,
            fieldType: item.dataType
          }
        })
      })
    },
    // 增加如果那么分单盒子
    addBox() {
      this.ruleOpen = true
    },
    // 保存父元素
    addParentRule() {
      this.ruleForm.formId = this.formId
      this.ruleForm.type = "0"
      addRule(this.ruleForm).then(response => {
        this.$modal.msgSuccess("新增成功");
        this.ruleOpen = false
        this.getParent()
        this.boxes = []
        this.rules = []
      })
    },
    // 增加规则
    addRule(boxIndex,ruleId,formId) {
      this.boxes[boxIndex].rules.push({
        formId: formId, //外层表单id
        groupId: ruleId, // 父元素id
        fieldName: {
          value: '',
          label: '',
          type: ''
        },
        condition: '',
        isStatic: '',
        staticValue: '',
        dynamicValue: ''
      });
    },
    // 保存子元素
    addChildRule() {
      for (let i = 0; i < this.boxes.length; i++) {
        const rules = this.boxes[i].rules;
        for (let j = 0; j < rules.length; j++) {
          const rule = rules[j];
          if (!rule.columnCondition || !rule.fieldName || !rule.isStatic || (rule.isStatic === '1' && !rule.staticValue) || (rule.isStatic === '0' && !rule.dynamicValue)) {
            this.$message.error('请填写所有字段！');
            return;
          }
        }
      }
      var parentForm = []
      var childForm = {}
      for (let i = 0; i < this.boxes.length; i++) {
        const parent = this.boxes[i]
        console.log("this.boxes[i] == ",this.boxes[i],"parent == ", parent)
        childForm.formId = parent.formId
        childForm.groupId = parent.ruleId
        childForm.type = "1"
        var child = parent.rules
        console.log("child == ", child)
        for (let j = 0; j < child.length; j++) {
          child[j].formId= childForm.formId
          child[j].type= childForm.type
          const selected = this.fieldNameOption.find(option => option.fieldName === child[j].fieldName);
          child[j].fieldType = selected == undefined ? "text" : selected.fieldType;
          parentForm.push(child[j])
        }
      }
      console.log("parentForm表单:",parentForm)
      addRuleBatch(parentForm).then(response => {
        this.$modal.msgSuccess("分单规则定义成功");
        this.$emit("handleClose",false)
        this.openSelect=false
        this.boxes = []
        this.rules = []
      })
    },
    // 删除如果那么分单盒子
    deleteBox(boxIndex,ruleId) {
      console.log(boxIndex,ruleId)
      if(ruleId != undefined && ruleId != null){
        this.$modal.confirm('是否确认删除所选数据项？').then(function () {
          return delParentRule(ruleId)
        }).then(() => {
          this.$modal.msgSuccess("删除成功");
          this.boxes.splice(boxIndex, 1);
        }).catch(() => {});
      }
    },
    // 删除规则
    deleteRule(boxIndex, ruleIndex, rule) {
      console.log(rule)
      if(rule.ruleId != null) {
        this.$modal.confirm('是否确认删除？').then(function () {
          return delChildRule(rule.ruleId)
        }).then(() => {
          this.boxes[boxIndex].rules.splice(ruleIndex, 1);
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      } else {
        this.$modal.confirm('是否确认删除？').then(() => {
          this.boxes[boxIndex].rules.splice(ruleIndex, 1);
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },
    // 根据表头下拉框渲染判断符号下拉框
    getFuhaoOptions(fieldType) {
      // console.log(fieldType)
      this.fuhaoOption = []
      if(fieldType == 'INT'||fieldType == 'BIGINT'||fieldType == 'DEC'||fieldType == 'NUMERIC'||fieldType == 'NUMBER'||fieldType == 'INTEGER'){
        // console.log("1：数值",this.dict.type.form_rule_condition_number)
        this.fuhaoOption = this.dict.type.FORM_RULE_CONDITION_NUMBER
      } else if( fieldType == 'DATE'||fieldType == 'TIME'||fieldType == 'DATETIME'||fieldType == 'TIMESTAMP'){
        // console.log("3:日期",this.dict.type.form_rule_condition_date)
        this.fuhaoOption = this.dict.type.FORM_RULE_CONDITION_DATE
      } else if(fieldType == 'VARCHAR'||fieldType == 'VARCHAR2'||fieldType == 'TEXT' ){
        // console.log("5:文本",this.dict.type.form_rule_condition_text)
        this.fuhaoOption = this.dict.type.FORM_RULE_CONDITION_TEXT
      }else {
        this.fuhaoOption = this.dict.type.FORM_RULE_CONDITION_TEXT
      }
    },
    // 获取数据渲染页面
    getParent(){
      console.log(1234567890)
      this.form = {
        formId: this.formId
      }
      ruleList(this.form).then(response => {
        // console.log(response)
        for (let i = 0; i < response.length; i++) {
          this.boxes.push({
            rules: [], // 每个box中的规则数据
            ruleId: response[i].ruleId, // 父元素id
            conditionName: response[i].conditionName,
            formId: response[i].formId // 外层表单id
          })
          console.log(this.boxes[i].ruleId)
          childList({groupId: this.boxes[i].ruleId}).then(response => {
            for (let j = 0; j < response.length; j++) {
              console.log('子元素',response[j])
              this.boxes[i].rules.push(response[j])
            }
          })
        }
        // console.log(this.boxes.length)
        // for (let j = 0; j < this.boxes.length; j++) {
        //   console.log(this.boxes[j].ruleId)
        //   childList({groupId: this.boxes[j].ruleId}).then(response => {
        //     for (let k = 0; k < response.length; k++) {
        //       console.log('子元素',response[k])
        //       this.boxes[j].rules.push(response[k])
        //     }
        //   })
        // }
      })
    },
    /** 查询分单规则列表 */
    getList() {
      this.loading = true;
      listRULE(this.queryParams).then(response => {
        this.RULEList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ruleId: null,
        formId: null,
        fieldName: null,
        condition: null,
        fieldType: null,
        isStatic: null,
        dynamicValue: null,
        staticValue: null,
        conditionName: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ruleId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleClose(){
      this.boxes = []
      this.rules = []
      this.openSelect=false
      this.$emit("handleClose",false)
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加分单规则";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ruleId = row.ruleId || this.ids
      getRULE(ruleId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改分单规则";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ruleId != null) {
            updateRULE(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRULE(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ruleIds = row.ruleId || this.ids;
      this.$modal.confirm('是否确认删除所选数据项？').then(function() {
        return delRULE(ruleIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('archive/RULE/export', {
        ...this.queryParams
      }, `RULE_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 30px);
  max-width: calc(100% - 30px);
}

::v-deep .el-dialog .el-dialog__body {
  flex: 1;
  overflow: auto;
}

.box {
  //border: 1px solid black;
  margin-top: 5px;
  padding: 1%;
}

.rule-main li {
// float: left;
  margin: 0 3% 0 0;
}
</style>
